package site.teamo.biu.net.common.web.entity;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import site.teamo.biu.net.common.web.mapper.SystemConfigMapper;

import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @param id             配置名称
 * @param show           是否展示标识
 * @param defaultContent 默认值产生器
 * @author haocongshun
 * @date 2023/06/07 15:25:47
 */
public record SystemConfig(String id, String name, boolean show, Supplier<String> defaultContent) {

    public SystemConfigDO toSystemConfigDO() {
        return new SystemConfigDO()
                .setId(this.id)
                .setName(this.name)
                .setContent(defaultContent.get());
    }

    public SystemConfigDO toSystemConfigDO(String value) {
        return new SystemConfigDO()
                .setId(this.id)
                .setName(this.name)
                .setContent(value);
    }


    public String getContent(SystemConfigMapper mapper) {
        return mapper.selectById(this.id).getContent();
    }

    public <T> T getContent(SystemConfigMapper mapper, Class<T> tClass) {
        return JSON.parseObject(mapper.selectById(this.id).getContent(), tClass);
    }

    public <K, V> Map<K, V> getContent(SystemConfigMapper mapper, Class<K> kClass, Class<V> vClass) {
        return JSON.parseObject(mapper.selectById(this.id).getContent(), new TypeReference<Map<K, V>>() {
        });
    }

    public <T> List<T> getContentList(SystemConfigMapper mapper, Class<T> tClass) {
        return JSON.parseArray(mapper.selectById(this.id).getContent(), tClass);
    }

    public boolean setContent(SystemConfigMapper mapper, String content) {
        return mapper.updateById(this.toSystemConfigDO(content)) > 0;
    }

}
